package com.lzw.bluetoothpractice.Activitys;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.text.Layout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzw.bluetoothpractice.Adapters.SendAdapter;
import com.lzw.bluetoothpractice.Adapters.SendMessageAdapter;
import com.lzw.bluetoothpractice.Adapters.UserReadMessageListAdapter;
import com.lzw.bluetoothpractice.AppConfig;
import com.lzw.bluetoothpractice.Models.SendMessage;
import com.lzw.bluetoothpractice.Models.UserDoctorMessage;
import com.lzw.bluetoothpractice.Models._User;
import com.lzw.bluetoothpractice.MyApplication;
import com.lzw.bluetoothpractice.R;
import com.lzw.bluetoothpractice.Utils.AppUtil;
import com.lzw.bluetoothpractice.Utils.SharePreferenceUtils;
import com.lzw.bluetoothpractice.bean.Messages;
import com.lzw.bluetoothpractice.bean.SystemUserListBean;
import com.lzw.bluetoothpractice.bean.UserDoctorMessageBean;
import com.lzw.bluetoothpractice.network.HeadAssmblyUtils;
import com.lzw.bluetoothpractice.network.RetrofitManager;
import com.lzw.bluetoothpractice.network.api.RequestApi;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMTextMessage;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.newim.core.BmobIMClient;
import cn.bmob.newim.core.ConnectionStatus;
import cn.bmob.newim.db.BmobIMDBManager;
import cn.bmob.newim.listener.MessageSendListener;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static cn.bmob.newim.core.BmobIMClient.getContext;

public class SendMessageActivity extends BaseActivity{

    private Map<String, String> keyMap;
    private EditText jg_details_edit;
  //  private BmobIMConversation mConversationManager;
   // private SendMessageAdapter adapter;
    private SendAdapter sendAdapter;
  //  private ListView listView;
    private BmobIMDBManager bmobIMDBManager;
    private RecyclerView recyclerView;
    final private List<BmobIMMessage> messagesList=new ArrayList<BmobIMMessage>();
    String targetId = "";
    final long i=1;
   // private List<BmobIMMessage> messages = new ArrayList<BmobIMMessage>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_message);
        Intent intent=getIntent();
    //    BmobIMConversation conversation = (BmobIMConversation) intent.getSerializableExtra("conversation");
     //  mConversationManager = BmobIMConversation.obtain(BmobIMClient.getInstance(), conversation);
        ;
        String Name=intent.getStringExtra("Name");
        String Head=intent.getStringExtra("Head");
        String ID=intent.getStringExtra("ID");
       // listView=findViewById(R.id.jg_details_recy);
        recyclerView=findViewById(R.id.jg_details_recy);
        targetId=ID;
        InitNavBar2(true,Name,false);

        sendAdapter = new SendAdapter(SendMessageActivity.this);
        recyclerView.setLayoutManager(new LinearLayoutManager(SendMessageActivity.this));
        initMyMessage();
        jg_details_edit=fd(R.id.jg_details_edit);
        jg_details_edit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                switch (i) {
                    case EditorInfo.IME_ACTION_SEND:

                        String text = textView.getEditableText().toString();//text即发送的消息


                       if (text.trim().equals("")) {
                            Toast.makeText(SendMessageActivity.this, "请输入内容", Toast.LENGTH_SHORT).show();
                        } else {

                           SendMessage(text.trim());
                            textView.setText("");
                         // mConversationManager.sendMessage(message,listener);
                             }
                        break;
                    default:
                        break;
                }
                return true;
            }
        });

    }



    private void initMyMessage(){
        try {
            keyMap = HeadAssmblyUtils.HeadAssembly("/dev-api/android/UserDoctorMessage/researchDetail");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String accessToken = SharePreferenceUtils.getString(MyApplication.getContext(),"access_token",null);;
        String userid = SharePreferenceUtils.getString(MyApplication.getContext(),"userId",null);
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).researchDetail(Long.parseLong(userid),Long.parseLong(targetId),"1", AppUtil.getVersionCode() + "", accessToken ,keyMap.get("gmtStr"), keyMap.get("contentMD5"), keyMap.get("hmacCode")).
                observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

                Log.e("我的医生：",e.getMessage()+"");

            }

            @Override
            public void onNext(JSONObject json) {

                UserDoctorMessageBean userDoctorMessageBean = JSON.parseObject(json.toString(), UserDoctorMessageBean.class);
                if(userDoctorMessageBean.getCode()==200){

                    //Article article=new Article();
                    LinearLayoutManager linearLayoutManager2=new LinearLayoutManager(SendMessageActivity.this);
                    linearLayoutManager2.setOrientation(LinearLayoutManager.VERTICAL);


                    sendAdapter.updateData(userDoctorMessageBean.getData());
                    recyclerView.setAdapter(sendAdapter);


                }else {
                    Toast toast=Toast.makeText(SendMessageActivity.this,"查询留言记录失败",Toast.LENGTH_LONG);
                    toast.show();
                }


            }
        });

    }

    private void SendMessage(String content){
        try {
            keyMap = HeadAssmblyUtils.HeadAssembly("/dev-api/android/UserDoctorMessage/researchDetail");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String accessToken = SharePreferenceUtils.getString(MyApplication.getContext(),"access_token",null);;
        String userid = SharePreferenceUtils.getString(MyApplication.getContext(),"userId",null);

        UserDoctorMessage userDoctorMessage=new UserDoctorMessage();
        userDoctorMessage.setMesUserId(Long.parseLong(userid));
        userDoctorMessage.setMesDoctorId(Long.parseLong(targetId));
        userDoctorMessage.setMesContent(content);
        userDoctorMessage.setMesType("0");
        userDoctorMessage.setMesStatus("1");
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).addUserDoctorMessage(userDoctorMessage,"1", AppUtil.getVersionCode() + "", accessToken ,keyMap.get("gmtStr"), keyMap.get("contentMD5"), keyMap.get("hmacCode")).
                observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

                Log.e("我的医生：",e.getMessage()+"");

            }

            @Override
            public void onNext(JSONObject json) {

                UserDoctorMessageBean userDoctorMessageBean = JSON.parseObject(json.toString(), UserDoctorMessageBean.class);
                if(userDoctorMessageBean.getCode()==200){

                    initMyMessage();
                    //Article article=new Article();



                }else {
                    Toast toast=Toast.makeText(SendMessageActivity.this,"添加留言记录失败",Toast.LENGTH_LONG);
                    toast.show();
                }


            }
        });

    }
  /*  *//**
     * 加载消息历史，从数据库中读出
     *//*
    private List<BmobIMMessage> initMsgData() {
        List<BmobIMMessage> list = BmobDB.create(this).queryMessages(targetId,MsgPagerNum);
        return list;
    }
*/
    /**
     * 界面刷新
     * @Title: initOrRefresh
     * @Description: TODO
     * @param
     * @return void
     * @throws
     */
  /*  private void initOrRefresh() {
        if (adapter != null) {
            if (MyMessageReceiver.mNewNum != 0) {// 用于更新当在聊天界面锁屏期间来了消息，这时再回到聊天页面的时候需要显示新来的消息
                int news=  MyMessageReceiver.mNewNum;//有可能锁屏期间，来了N条消息,因此需要倒叙显示在界面上
                int size = initMsgData().size();
                for(int i=(news-1);i>=0;i--){
                    adapter.add(initMsgData().get(size-(i+1)));// 添加最后一条消息到界面显示
                }
                listView.setSelection(adapter.getCount() - 1);
            } else {
                adapter.notifyDataSetChanged();
            }
        } else {
            adapter = new SendMessageAdapter(initMsgData(),this,);
            listView.setAdapter(adapter);
        }
    }*/
}
